import requests
from bs4 import BeautifulSoup


def crawl_lottery_info():
    url = "https://www.cwl.gov.cn/ygkj/kjgg/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
    }

    try:
        # 发送请求获取页面内容
        response = requests.get(url, headers=headers, timeout=1000)
        response.encoding = "UTF-8"  # 页面声明为UTF-8编码
        soup = BeautifulSoup(response.text, "html.parser")
        # 双色球
        ssq_code = soup.find('div', class_='ssqQh-dom').text.strip()
        ssq_red_info = soup.find('div', class_='ssqRed-dom').text.strip()
        ssq_blue = soup.find('div', class_='ssqBlue-dom').text.strip()
        print(f"双色球->期号{ssq_code} 红色球：{ssq_red_info} 蓝色球：{ssq_blue}")
        # 3d
        d3_code = soup.find('div', class_='fcQh-dom').text.strip()
        d3_red_info = soup.find('div', class_='fcBlue-dom').text.strip()
        print(f"3d->期号{d3_code} 号码：{d3_red_info}")
        # 快乐8
        kl8_code = soup.find('div', class_='kl8Qh-dom').text.strip()
        kl8_red_info = soup.find('div', class_='klRed-dom').text.strip()
        print(f"快乐8->期号{kl8_code} 号码：{kl8_red_info}")
        # 七乐彩
        qlc_code = soup.find('div', class_='qlcQh-dom').text.strip()
        qlc_red_info = soup.find('div', class_='qclRed-dom').text.strip()
        qlc_blue = soup.find('div', class_='qclBlue-dom').text.strip()
        print(f"七乐彩->期号{qlc_code} 红色球：{qlc_red_info} 蓝色球：{qlc_blue}")
        return {
            'ssq_code': ssq_code,
            'ssq_red_info': ssq_red_info,
            'ssq_blue': ssq_blue,
            'd3_code': d3_code,
            'd3_red_info': d3_red_info,
            'kl8_code': kl8_code,
            'kl8_red_info': kl8_red_info,
            'qlc_code': qlc_code,
            'qlc_blue': qlc_blue,
            'qlc_red_info': qlc_red_info
        }
    except requests.exceptions.RequestException as e:
        print(f"请求出错：{e}")
    except Exception as e:
        print(f"解析出错：{e}")


def process_lottery_data():
    data = crawl_lottery_info()
    """处理彩票数据，将字符串形式的列表转换为实际列表，单个数字则直接提取"""
    processed = {}
    for key, value in data.items():
        # 判断是否是包含列表的字符串
        if key.endswith(('_red_info', '_blue')):
            try:
                # 移除首尾的方括号
                content = value.strip('[]')
                # 按逗号分割并去除空格
                items = [item.strip() for item in content.split(',')]

                # 如果只有一个元素，则直接提取该元素，而不是保留列表
                if len(items) == 1:
                    processed[key] = items[0]
                else:
                    processed[key] = items

            except Exception as e:
                print(f"处理 {key} 时出错: {e}")
                processed[key] = value  # 出错时保留原始值
        else:
            processed[key] = value
    return processed
# print(process_lottery_data(crawl_lottery_info()))